import 'package:flutter/material.dart';

/**
 * 数据管理类(解决一级一级的往下传递数据)
 */
class MyData extends InheritedWidget {
  final int data; //需要在子组件中共享的数据（保存点击次数）

  ///构造方法
  const MyData({required this.data, required Widget mchild})
      : super(child: mchild);

  ///定义一个便捷方法，方便子组件中的Widget去获取共享的数据
  static MyData? of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<MyData>();
  }

  ///该回调决定当前data发生变化时，是否通知子组件依赖data的Widget
  @override
  bool updateShouldNotify(MyData oldWidget) {
    ///如果返回true,子部件中依赖数据的Widget（build函数中有数据）的didChangeDependencies会调用
    return oldWidget.data != data;
  }
}

/**
 * 数据共享InheritedWidget
 */
class InheritedDemo extends StatefulWidget {
  const InheritedDemo({super.key});

  @override
  State<InheritedDemo> createState() => _InheritedDemoState();
}

class _InheritedDemoState extends State<InheritedDemo> {
  int _count = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('数据共享InheritedWidget'),
        centerTitle: true,
      ),

      ///数据共享，解决多层传递参数显示
      body: MyData(
        data: _count,
        mchild: Column(
          children: [
            ElevatedButton(
                onPressed: () {
                  _count++;
                  setState(() {});
                },
                child: Text('我是按钮')),
            Test1(_count),
          ],
        ),
      ),
    );
  }
}

class Test1 extends StatelessWidget {
  final int count;

  Test1(this.count);

  @override
  Widget build(BuildContext context) {
    return Test2(count);
  }
}

class Test2 extends StatelessWidget {
  final int count;

  Test2(this.count);

  @override
  Widget build(BuildContext context) {
    return Test3(count);
  }
}

class Test3 extends StatefulWidget {
  final int count;

  Test3(this.count);

  @override
  State<StatefulWidget> createState() {
    return _Test3State();
  }
}

/**
 *
 */
class _Test3State extends State<Test3> {
  @override
  void didChangeDependencies() {
    print('didChangeDependencies来了');
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    print('哥们我来了');
    return Center(
      ///通过构造方法一级一级传递过来的数据
      // child: Text(widget.count.toString()),
      ///数组共享
      child: Text(MyData.of(context)!.data.toString()),
    );
  }
}
